import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  Platform,
  AppState,
  AppStateStatus,
  KeyboardAvoidingView,
  RefreshControl,
} from 'react-native';
import { useLocalSearchParams, useRouter, Stack } from 'expo-router';
import { MaterialIcons } from '@expo/vector-icons';
import { artworkService, communityService } from '../../utils/api/services';
import { ArtworkResponse, CommentResponse } from '../../utils/api/types';
import { useTheme } from '../../components/theme/ThemeContext';
import { useAuth } from '../../store/auth/AuthContext';
import MediaPlayer from '../../components/artwork/MediaPlayer';
import { CommentSection } from '../../components/artwork/CommentSection';

interface CommentsListResponse {
  code: number;
  message: string;
  data: {
    data: CommentResponse[];
    total: number;
    page: number;
    size: number;
  };
}

export default function ArtworkDetail() {
  const { id } = useLocalSearchParams();
  const router = useRouter();
  const { theme } = useTheme();
  const { user } = useAuth();
  const [artwork, setArtwork] = useState<ArtworkResponse | null>(null);
  const [comments, setComments] = useState<CommentResponse[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [hasMoreComments, setHasMoreComments] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const COMMENTS_PER_PAGE = 10;

  // 监听应用状态变化
  useEffect(() => {
    const subscription = AppState.addEventListener('change', handleAppStateChange);
    return () => {
      subscription.remove();
    };
  }, []);

  // 处理应用状态变化
  const handleAppStateChange = useCallback((nextAppState: AppStateStatus) => {
    if (nextAppState !== 'active') {
      // MediaPlayer组件会自己处理媒体暂停
    }
  }, []);

  // 加载评论
  const loadComments = useCallback(async (page: number = 1, refresh: boolean = false) => {
    if (!id) return;

    try {
      // 如果正在加载更多，阻止重复请求
      if (!refresh && isLoadingMore) return;
      
      // 设置加载状态
      if (!refresh) {
        setIsLoadingMore(true);
      }

      console.log('开始加载评论:', { page, refresh, isLoadingMore, currentPage });
      
      const response = (await communityService.listComments({
        work_id: Number(id),
        page,
        size: COMMENTS_PER_PAGE
      }) as unknown) as CommentsListResponse;

      console.log('评论加载响应:', response);

      if (response?.code === 200 && response?.data) {
        const commentsList = response.data.data;
        const { total } = response.data;

        console.log('评论数据:', {
          commentsList: commentsList.length,
          total,
          currentPage: page,
          COMMENTS_PER_PAGE,
          refresh
        });

        // 更新评论总数
        setTotal(total);

        // 更新评论列表
        if (refresh) {
          setComments(commentsList);
          setCurrentPage(1);
        } else {
          setComments(prev => [...prev, ...commentsList]);
          setCurrentPage(page);
        }

        // 更新是否有更多评论的状态
        const hasMore = commentsList.length > 0 && page * COMMENTS_PER_PAGE < total;
        console.log('更新加载更多状态:', {
          currentPage: page,
          total,
          hasMore,
          commentsLength: commentsList.length,
          currentCommentsTotal: (page * COMMENTS_PER_PAGE)
        });
        
        setHasMoreComments(hasMore);
      }
    } catch (error) {
      console.error('加载评论失败:', error);
    } finally {
      setIsLoadingMore(false);
    }
  }, [id]);

  // 分离作品详情加载逻辑
  const loadArtworkDetail = useCallback(async () => {
    if (!id) return;
    
    try {
      setIsLoading(true);
      setError(null);

      const artworkData = await artworkService.getArtwork(Number(id));
      
      if (artworkData?.code === 200 && artworkData?.data) {
        setArtwork(artworkData.data);
        await loadComments(1, true);
      }
    } catch (error) {
      console.error('加载失败:', error);
      setError('加载失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  }, [id, loadComments]);

  // 初始加载
  useEffect(() => {
    loadArtworkDetail();
  }, [loadArtworkDetail]);

  const handleBack = () => {
    router.back();
  };

  const handleSubmitComment = useCallback(async (content: string) => {
    if (!user?.id) {
      router.push('/user/login');
      return;
    }

    try {
      const response = await communityService.createComment({
        work_id: Number(id),
        content: content,
        user_id: Number(user.id),
      });

      if (response?.code === 200 && response?.data) {
        // 将新评论添加到列表开头
        setComments(prev => [(response.data as unknown) as CommentResponse, ...prev]);
        // 更新评论总数
        setTotal(prev => prev + 1);
      }
    } catch (error) {
      console.error('发送评论失败:', error);
      // TODO: 添加错误提示
    }
  }, [id, user?.id, router]);

  const handleLoadMoreComments = useCallback(() => {
    console.log('触发加载更多评论:', {
      currentPage,
      hasMoreComments,
      isLoadingMore
    });
    
    if (hasMoreComments && !isLoadingMore) {
      const nextPage = currentPage + 1;
      console.log('加载下一页:', nextPage);
      loadComments(nextPage, false);
    }
  }, [hasMoreComments, isLoadingMore, currentPage, loadComments]);

  const handleRefreshComments = useCallback(() => {
    if (isLoading || isLoadingMore) return;
    setIsLoading(true);
    loadComments(1, true).finally(() => {
      setIsLoading(false);
    });
  }, [loadComments, isLoading, isLoadingMore]);

  const renderLoadingOrError = () => (
    <View style={[styles.container, { backgroundColor: theme.colors.background }]}>
      <Stack.Screen 
        options={{
          headerShown: true,
          headerTitle: '作品详情',
          headerStyle: { backgroundColor: theme.colors.card },
          headerTintColor: theme.colors.text,
          headerLeft: () => (
            <TouchableOpacity onPress={handleBack}>
              <MaterialIcons name="arrow-back" size={24} color={theme.colors.text} />
            </TouchableOpacity>
          )
        }} 
      />
      <View style={styles.centerContainer}>
        <Text style={[styles.messageText, { color: theme.colors.text }]}>
          {error || (isLoading ? '加载中...' : '')}
        </Text>
      </View>
    </View>
  );

  if (isLoading || error || !artwork) {
    return renderLoadingOrError();
  }

  return (
    <KeyboardAvoidingView 
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 88 : 0}
    >
      <Stack.Screen 
        options={{
          headerShown: true,
          headerTitle: artwork.title || '作品详情',
          headerStyle: { backgroundColor: theme.colors.card },
          headerTintColor: theme.colors.text,
          headerLeft: () => (
            <TouchableOpacity onPress={handleBack}>
              <MaterialIcons name="arrow-back" size={24} color={theme.colors.text} />
            </TouchableOpacity>
          )
        }} 
      />
      
      <ScrollView 
        style={[styles.scrollView, { backgroundColor: theme.colors.background }]}
        contentContainerStyle={styles.scrollViewContent}
        refreshControl={
          <RefreshControl
            refreshing={isLoading}
            onRefresh={handleRefreshComments}
            tintColor={theme.colors.primary}
            colors={[theme.colors.primary]}
          />
        }
      >
        <View style={[styles.mediaAndInfoContainer, { backgroundColor: theme.colors.background }]}>
          <MediaPlayer
            artwork={artwork}
            onMediaStateChange={(isPlaying) => {
              // 处理媒体状态变化
            }}
          />
          
          <View style={[styles.contentContainer, { backgroundColor: theme.colors.card }]}>
            <Text style={[styles.title, { color: theme.colors.text }]}>
              {artwork.title}
            </Text>
            <Text style={[styles.description, { color: theme.colors.text }]}>
              {artwork.description}
            </Text>
          </View>
        </View>

        <CommentSection
          comments={comments}
          total={total}
          isLoadingMore={isLoadingMore}
          hasMoreComments={hasMoreComments}
          onLoadMore={handleLoadMoreComments}
          onSubmitComment={handleSubmitComment}
          onRefresh={handleRefreshComments}
        />
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  scrollViewContent: {
    flexGrow: 1,
  },
  mediaAndInfoContainer: {
    width: '100%',
  },
  contentContainer: {
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  description: {
    fontSize: 16,
    lineHeight: 24,
  },
  centerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  messageText: {
    fontSize: 16,
  },
}); 